import { RegisterComponent } from "@feng3d/ecs";
import { Camera } from "../../thirdparty/three/imports";
import { Component3D } from "../core/Component3D";

declare module "@feng3d/ecs"
{
    interface ComponentMap { Camera3D: Camera3D; }
}

/**
 * 3D透视摄像机，包装`three`中`PerspectiveCamera`。
 */
@RegisterComponent({ name: 'Camera3D' })
export class Camera3D extends Component3D
{
    /**
     * @private
     */
    get _camera()
    {
        return this.__camera;
    }
    set _camera(v)
    {
        Camera3D._map.delete(this.__camera);
        this.__camera = v;
        Camera3D._map.set(this.__camera, this);
    }
    protected __camera: Camera;

    init()
    {
        super.init();

        this._entity._group.add(this._camera);
        this._entity.isCamera = true;
    }

    destroy(): void
    {
        this._entity._group.remove(this._camera);
        this._entity.isCamera = false;

        this._camera = null;

        super.destroy();
    }

    updateMatrixWorld()
    {
        if (!this.entity.parent && this.entity._group.matrixWorldAutoUpdate === true)
        {
            this.entity._group.updateMatrixWorld();
            this._camera.updateMatrixWorld();
        }
    }

    static get(camera: Camera)
    {
        const camera3D = this._map.get(camera);

        return camera3D;
    }
    private static _map = new Map<Camera, Camera3D>();
}
